package com.handu.luna.boss.controller;

import java.util.LinkedList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.BossException;
import com.handu.luna.core.domain.Mall;
import com.handu.luna.core.domain.article.ArticleCategory;
import com.handu.luna.core.domain.article.ArticleList;


@Controller
@RequestMapping("/article/category/*")
public class ArticleCategoryController extends BaseController{
	
    @RequestMapping(value="index")
    public BossModel index(){
    	Mall mall=new Mall();
    	mall.articleInit();   
       /* List<ArticleCategory> list = mall.getAllArticleCategories();
    	ArticleCategory a = new ArticleCategory(0,"顶级分类");
    	a.setParent_id(0);
    	a.setSubCategories(mall.getAllArticleCategories());
    	list.add(0,a);*/
    	
    	//LinkedList <ArticleCategory> list =new LinkedList<ArticleCategory>(context.getArticleCategoryRepository().findAll());
		//list.add(0,new ArticleCategory(0,"顶级分类"));
    	return createModel("article/category/index").add("categories",mall.getAllArticleCategories());	  //mall.getAllArticleCategories()
    }
	@RequestMapping(value="add")
	public BossModel add(){  	
		LinkedList <ArticleCategory> list =new LinkedList<ArticleCategory>(context.getArticleCategoryRepository().findAll());
		list.add(0,new ArticleCategory(0,"顶级分类"));
		
	    ArticleCategory category = new ArticleCategory();
	    category.setIs_show(true);  
	    category.setSort_order(100);
	    return createModel("article/category/save").add("articleCategory", category).add("cateParents",list);	
	}
	
	
	@RequestMapping(value="delete",method = RequestMethod.POST)
	public BossModel delete(long id){  //final BindingResult bindingResult
		
		/*boolean flag = false;
		if(beforeDelete(id, flag)){
			throw new BossException("顶级分类不可移除，或者该分类下存在文章！");
		}*/
		List<ArticleCategory> getIncludeParent = context.getArticleCategoryRepository().getAllByCatIdNew(String.valueOf(id));
		List<ArticleList> articles = context.getArticleListRepository().findAll(id) ;//如果父类下没有文章，但是子分类下有文章，当删除父类的时候，也不允许删除！
	   
		if(!getIncludeParent.isEmpty()){
			throw new BossException("该分类下存在子分类，不可以将其移除!");   //顶级分类不可移除，或者该分类下存在文章！
		}else if(!articles.isEmpty()){
			throw new BossException("该分类下存在文章，不可以将其移除!"); 
		}else{
			context.getArticleCategoryRepository().delete(id);
		}
		
		Mall mall = new Mall();
		mall.articleInit();
		return createModel("article/category/categorys_table").add("categories", mall.getAllArticleCategories());
	
	}
	
	

	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
     
		Mall mall=new Mall();
    	mall.articleInit();       
    	List<ArticleCategory> list = mall.getAllArticleCategories();
    	ArticleCategory a = new ArticleCategory(0,"顶级分类");
    	a.setParent_id(-1);
    	a.setSubCategories(mall.getAllArticleCategories());
    	list.add(0,a);
		return createModel("article/category/save").add("articleCategory", context.getArticleCategoryRepository().findOne(id)).add("cateParents",list);
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final ArticleCategory articleCategory,final BindingResult bindingResult,RedirectAttributes redirectAttributes)
	{
		String message = "";
		
		Mall mall=new Mall();
    	mall.articleInit(); 
    	List<ArticleCategory> list = mall.getAllArticleCategories();
    	ArticleCategory a = new ArticleCategory(0,"顶级分类");
    	a.setParent_id(0);
    	a.setSubCategories(mall.getAllArticleCategories());
    	list.add(0,a);
		if(bindingResult.hasErrors()){
			return createModel("article/category/save").add("cateParents", list);
		}
		//同级名称不能重复
		//List<ArticleCategory> CategoryNameCheck;
		
		
		if(articleCategory.getId()==null){   //添加
			if(articleCategory.getParent_id()!=0){
			//获得所父类的  子子孙孙
			List<ArticleCategory> getIncludeParent = context.getArticleCategoryRepository().getAllByCatIdNew(String.valueOf(articleCategory.getParent_id()));
			for (ArticleCategory lists : getIncludeParent) {
				if(lists.getName().equals(articleCategory.getName()) && (lists.getParent_id()==articleCategory.getParent_id())){
					message = "所添加的文章分类名称：" + articleCategory.getName()+ "在同级分类下已存在";
					bindingResult.addError(new FieldError("category", "name", message));
					return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories()); 
				}
			  }
			}else{
				List<ArticleCategory> topCats = context.getArticleCategoryRepository().getAllByCatId(articleCategory.getParent_id());
				for (ArticleCategory lists : topCats) {
					if(articleCategory.getName().equals(lists.getName()) && (lists.getParent_id()==articleCategory.getParent_id())){
						message = "所添加的文章分类名称：" + articleCategory.getName()+ "在同级分类下已存在";
						bindingResult.addError(new FieldError("category", "name", message));
						return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories());
					}
				}				
			}
		}else{	   //修改		
			//ArticleCategory CategoryNameCheckById = context.getArticleCategoryRepository().findOne(articleCategory.getParent_id());
			ArticleCategory oneinfo = context.getArticleCategoryRepository().findOne(articleCategory.getId());
			if(articleCategory.getParent_id()!=0){
			//获得所选择分类的  子子孙孙
			List<ArticleCategory> getIncludeParent = context.getArticleCategoryRepository().getAllByCatIdNew(String.valueOf(articleCategory.getParent_id()));
			for (ArticleCategory lists : getIncludeParent) {
				if(lists.getName().equals(articleCategory.getName()) && (lists.getId()!=articleCategory.getId()) && (lists.getParent_id()==articleCategory.getParent_id())){
					message = "所修改的文章分类名称：" + articleCategory.getName()+ "在同级分类下已存在";
					bindingResult.addError(new FieldError("category", "name", message));
					return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories()); 
				}
			  }
			}else{
				List<ArticleCategory> topCats = context.getArticleCategoryRepository().getAllByCatId(articleCategory.getParent_id());
				for (ArticleCategory lists : topCats) {
					if(articleCategory.getName().equals(lists.getName()) && (lists.getId()!=articleCategory.getId()) && (lists.getParent_id()==articleCategory.getParent_id())){
						message = "所修改的文章分类名称：" + articleCategory.getName()+ "在同级分类下已存在";
						bindingResult.addError(new FieldError("category", "name", message));
						return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories());
					}
				}				
			}
			
			//寻找自己的孩子
			//List<ArticleCategory> getIncludeParent = context.getArticleCategoryRepository().getAllByCatIdNew(String.valueOf(articleCategory.getId()));
			if(oneinfo.getParent_id()==0 && articleCategory.getParent_id()!=0){
				bindingResult.addError(new FieldError("category", "parent_id", "顶级目录不可以修改"));
				return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories());
			}
			/*else if(oneinfo.getName().equals(articleCategory.getName())){   //else if(CategoryNameCheckById.getName().equals(articleCategory.getName())){ 如果新添加的分类名称与所选的分类名称相同，则不允许添加
				message = "文章分类名称：" + articleCategory.getName()+ "在同级下已存在";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories());   //??????			
			}*/
			else if(checkOnChange(articleCategory.getId(),articleCategory.getParent_id())){
				message = "父类不能修改成自己的子类！";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories()); 
			}else if(articleCategory.getId()==articleCategory.getParent_id()){   //至今没走此情况
				message = "不能选择本身的分类！";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories()); 
				
			}
		}
		
		if(null==articleCategory.getId()){
			message = "添加" +articleCategory.getName() +"成功";
			ArticleCategory getParentCollectionByCatId = context.getArticleCategoryRepository().findOne(articleCategory.getParent_id());
			if(getParentCollectionByCatId!=null){
				if(getParentCollectionByCatId.getParentCollection()!=""){
					articleCategory.setParentCollection(getParentCollectionByCatId.getParentCollection() + ","+ getParentCollectionByCatId.getId());//articleCategory.getParent_id()
				}else{
				    articleCategory.setParentCollection(String.valueOf(getParentCollectionByCatId.getId()));
				}
			}else{
				articleCategory.setParentCollection("");
			}
			//articleCategory.setParentCollection(getParentCollectionByCatId.getParentCollection() + ","+ articleCategory.getParent_id());
			context.getArticleCategoryRepository().save(articleCategory);
		}else{
			message = "修改" +articleCategory.getName() +"成功";
			//List<ArticleCategory> getIncludeParent = context.getArticleCategoryRepository().getAllByCatIdNew(String.valueOf(articleCategory.getId()));
			//获得被选分类的  “parentCollection”
			ArticleCategory getSelectCategoryParentCollection = context.getArticleCategoryRepository().findOne(articleCategory.getParent_id());
			if(getSelectCategoryParentCollection!=null){
				if(getSelectCategoryParentCollection.getParentCollection()==""){
					articleCategory.setParentCollection(String.valueOf(getSelectCategoryParentCollection.getId()));
				}else{
					articleCategory.setParentCollection(getSelectCategoryParentCollection.getParentCollection() + ","+ getSelectCategoryParentCollection.getId());  //articleCategory.getParent_id()
				}
			}
			else{
				articleCategory.setParentCollection("");
			}
			ArticleCategory oneinfo = context.getArticleCategoryRepository().findOne(articleCategory.getId());
			if(oneinfo.getParent_id()!=0 && articleCategory.getParent_id()!=0){   //判断所编的分类是不是  “顶级分类”
			  if(!replaceChildParentCollection(articleCategory.getId(),articleCategory.getParent_id() )){
				message = "编辑分类失败！";
			  }
			}
			context.getArticleCategoryRepository().save(articleCategory);
			
		}
		
		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:index");
		
	}
	
	
	//删除和编辑判断
/*	public boolean beforeDelete(long id,boolean flag){
		if(context.getArticleListRepository().has("catId", id)|| id==0){  //catId
			flag = true;
		}
		if(flag){
			
			return flag;
		}
		
		List<ArticleCategory> childs = context.getArticleCategoryRepository().getAllByCatId(id);
		
		if(childs.size()>0){
			for (ArticleCategory articleCategory : childs) {
				if(articleCategory.getId()!=0){
					List<ArticleList> articles = context.getArticleListRepository().findAll(articleCategory.getId()) ;//如果父类下没有文章，但是子分类下有文章，当删除父类的时候，也不允许删除！
				    if(!articles.isEmpty()){
				    	flag = true;
				    }
				}else{
				   beforeDelete(articleCategory.getId(), flag);
				}
			}
		}	
		return flag;
		
	}*/
	
	
	//编辑分类的判断
	@RequestMapping(value="check")
	public @ResponseBody boolean check(long id , long selectedId){
		return checkOnChange(id,selectedId);
	}
	
	public boolean checkOnChange(long id , long selectedId){
		
		List<ArticleCategory> childs = context.getArticleCategoryRepository().getAllByCatId(id);
		
		if(childs.size()>0){
			for (ArticleCategory articleCategory : childs) {
				if(articleCategory.getId() == selectedId){
					return true;
				}
			}
		}
		
		
		if(childs.size() >0){
			for (ArticleCategory articleCategory : childs) {
				if(checkOnChange(articleCategory.getId(), selectedId)){
					return true;
				}
			}
		}		
		return false;
	}
	
	
	//循环替换孩子的“parentCollection”   new
	public boolean replaceChildParentCollection(long id,long pId){
		
	//获得所选分类的  子子孙孙
	List<ArticleCategory> getIncludeParent = context.getArticleCategoryRepository().getAllByCatIdNew(String.valueOf(id));
	//获得所移动分类的“parentCollection”
	ArticleCategory replaceChildParentCollection = context.getArticleCategoryRepository().findOne(id);
	
	//获得被选择分类的 “parentCollection”
	ArticleCategory selectCatParentCollection = context.getArticleCategoryRepository().findOne(pId);
	if(selectCatParentCollection.getParentCollection()!=""){
		replaceChildParentCollection.setParentCollection(selectCatParentCollection.getParentCollection() + "," +selectCatParentCollection.getId());
	}else{
		replaceChildParentCollection.setParentCollection(String.valueOf(selectCatParentCollection.getId()));
	}
	
	for (ArticleCategory list : getIncludeParent) {   //循环孩子，将孩子的“parentCollection”  
		if(replaceChildParentCollection.getParentCollection()==""){
			list.setParentCollection(String.valueOf(replaceChildParentCollection.getId()));  //list.getParent_id()
		}else{
		    list.setParentCollection(replaceChildParentCollection.getParentCollection() + "," + replaceChildParentCollection.getId());  //list.getParent_id()
		}
		if(replaceChildParentCollection(list.getId() , list.getParent_id())){
			list.setParentCollection(list.getParentCollection());
			context.getArticleCategoryRepository().save(list);
			return true;
		}	
	}
	
	return true;

	}
}
